package main

import (
	"context"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

type User struct {
	gorm.Model
	CreditCard CreditCard
	CompanyID  int
	Company    Company
	Languages  []Language `gorm:"many2many:user_languages;"`
}
type Company struct {
	ID   int
	Name string
}
type CreditCard struct {
	gorm.Model
	Number string
	UserID uint
}

// 是否存在表
func ExistTable(mdb *gorm.DB) {
	if mdb.Migrator().HasTable(&User{}) {
		mdb.Migrator().DropTable(&User{})
		mdb.Migrator().DropTable(&CreditCard{})
		// mdb.Migrator().DropTable(&Language{})
	} else {
		mdb.AutoMigrate(&User{})
		mdb.AutoMigrate(&CreditCard{})
		// mdb.AutoMigrate(&Language{})
	}
}

type Cat struct {
	ID   int
	Name string
	Toy  Toy `gorm:"polymorphic:Owner;"`
}

type Dog struct {
	ID   int
	Name string
	Toy  Toy `gorm:"polymorphic:Owner;"`
}

type Toy struct {
	ID        int
	Name      string
	OwnerID   int
	OwnerType string
}

type Language struct {
	gorm.Model
	Name string
}

type Tag struct {
	ID     uint   `gorm:"primaryKey"`
	Locale string `gorm:"primaryKey"`
	Value  string
}

type Blog struct {
	ID         uint   `gorm:"primaryKey"`
	Locale     string `gorm:"primaryKey"`
	Subject    string
	Body       string
	Tags       []Tag `gorm:"many2many:blog_tags;"`
	LocaleTags []Tag `gorm:"many2many:locale_blog_tags;ForeignKey:id,locale;References:id,locale"`
	SharedTags []Tag `gorm:"many2many:shared_blog_tags;ForeignKey:id;References:id"`
}

func main() {
	db, err := Conn()
	if err != nil {
		panic(err)
	}
	users := []User{}
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()

	db.WithContext(ctx).Find(&users)
	// db.AutoMigrate(&Tag{})
	// db.AutoMigrate(&Blog{})
	// db.AutoMigrate(&Cat{})
	// db.AutoMigrate(&Dog{})
	// db.AutoMigrate(&Toy{})

	// db.Create(&Dog{Name: "dog1", Toy: Toy{Name: "toy1"}})
	//是否存在表
	// ExistTable(db)
	//批量添加
	// BatchCreate(MDB)
	// res := db.Model(&User{}).Create(&User{
	// 	Name: "小明",
	// 	Company: Company{
	// 		Name: "木星个",
	// 	},
	// })
	// println(res.RowsAffected)
	// db.Model(&Company{}).Delete(&Company{}, 1)

	// db.Model(&User{}).Create(&User{
	// 	Name:      "111",
	// 	CompanyID: 1,
	// })
	// var user []User
	// db.Model(&User{}).Preload("Company").Find(&user)
	// fmt.Printf("&v", user)
}

func Conn() (*gorm.DB, error) {
	dsn := "root:root@tcp(127.0.0.1:3306)/ant_study?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN: dsn,
	}), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix: "fa_",
			// SingularTable: false,
		},
	})
	if err != nil {
		return nil, err
	}

	sqlDb, err := db.DB()
	if err != nil {
		return nil, err
	}
	//设置空闲连接池中的最大连接数
	sqlDb.SetMaxIdleConns(10)
	//设置数据库的最大打开连接数
	sqlDb.SetMaxOpenConns(100)
	//设置连接可以重复使用的最长时间。
	sqlDb.SetConnMaxLifetime(time.Hour)
	return db, nil
}
